<template>
  <basic-dialog
    :fullscreen="true"
    :width="'80%'"
    :visible="visible"
    :title="'报价信息'"
    :ok-text="'完成报价'"
    :loadingBtn="addQuotationLoading"
    :handle-ok="handleFinishQuote"
    :othersLoadingBtn="computingCostsLoading"
    :other-text="'计算成本'"
    :handleOthers="handleShareFreight"
    :others1LoadingBtn="tmpQuotationLoading"
    :other1-text="'暂存'"
    :handleOthers1="handleSubmitTempQuote"
    :handle-close="handleCancelQuote"
    :showOthersBtn="true"
    :showOthers1Btn="!isQuoteDone"
    :show-close="false"
    :handleClosed="handleClosed"
  >
    <div class="form-wrap">
      <el-form
        ref="quoteForm"
        :model="quoteForm"
        :rules="formValidate"
        label-width="130px"
      >
        <el-col :span="8">
          <el-form-item label="供应商名称：" prop="supplierName">
            <el-input v-model="quoteForm.supplierName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商代码：" prop="supplierCode">
            <el-input v-model="quoteForm.supplierCode" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运费承担方：" prop="freightPayer">
            <el-select
              v-model="quoteForm.freightPayer"
              style="width: 100%"
              @change="freightPayerChange"
            >
              <el-option
                v-for="option in freightBearerList"
                :key="option.sysTypeId"
                :value="option.sysTypeId"
                :label="option.sysTypeName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运费：" prop="freightPrice">
            <el-input
              v-model.trim="quoteForm.freightPrice"
              :maxlength="32"
              show-word-limit
              :disabled="isOtherUndertaker()"
            />
          </el-form-item>
        </el-col>
        <!-- :disabled="isEligibleSupplier() || isSynergy" -->
        <el-col :span="8">
          <el-form-item label="发票类型：" prop="invoiceType">
            <el-select
              v-model="quoteForm.invoiceType"
              style="width: 100%"
              disabled
              @change="invoiceTypeChange"
            >
              <el-option
                v-for="option in invoiceTypeList"
                :key="option.sysTypeId"
                :value="option.sysTypeId"
                :label="option.sysTypeName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- :disabled="isEligibleSupplier() && !isMulttaxRate || isSynergy" -->
        <!-- option in isEligibleSupplier() && isMulttaxRate && !isSynergy -->
        <el-col :span="8">
          <el-form-item label="税率：" prop="taxRate">
            <el-select
              v-model="quoteForm.taxRate"
              style="width: 100%"
              :disabled="!isMulttaxRate"
            >
              <el-option
                v-for="option in (isMulttaxRate) ? taxRate2ListObj : taxrateArr"
                :key="option.sysTypeId"
                :value="option.sysTypeId"
                :label="option.sysTypeName"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
    </div>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix quote-info-detail">
        <span>报价明细</span>
        <div class="operating-area">
          <el-button
            class="search-btn"
            size="mini"
            type="primary"
            @click="handleSearchBidRecord"
          >查询定标记录</el-button>
          <div class="time-picker">
            <el-date-picker
              size="mini"
              style="margin-right: 10px;"
              v-if="this.queryParams.pageType !== 1"
              v-model="workableArrivalTime"
              placeholder="落实到货时间统一配置"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="'23:59:59'"
              @change="dateTimeChange"
            />
            <el-input
              size="mini"
              v-if="this.queryParams.pageType == 1"
              style="width: 200px; margin-right: 10px;"
              v-model.number="deliveryDate"
              placeholder="批量维护交货期"
              @input="deliveryDateChange"
            />
            <el-date-picker
              size="mini"
              v-model="priceExpireTime"
              placeholder="批量维护报价有效期"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="'23:59:59'"
              @change="priceExpireTimeChange"
            />
          </div>

          <el-button size="mini" type="primary" @click="handleExportQuoteDtl"
            >导出</el-button
          >
          <el-upload
            ref="importBatchFileUpload"
            class="upload-quote"
            action="/srm-api/sourceSkuQuote/importSkuQuote"
            :data="fileParam"
            :on-success="onUploadsuccessForBatch"
            :before-upload="beforeFileUploadForBatch"
            :on-error="onUploadErrorForBatch"
            :show-file-list="false"
          >
            <el-button size="mini" type="primary" :loading="importBtnLoading"
              >导入</el-button
            >
          </el-upload>
        </div>
      </div>
      <div class="edit-table">
        <pl-table
          ref="edti-table"
          use-virtual
          :excess-rows="50"
          height="500"
          :row-height="45"
          v-loading="tableLoading"
          stripe
          border
          size="mini"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
          :data="sourcingSkuQuoteList"
        >
          <pl-table-column
            fit
            v-for="item in columns"
            :key="item.prop"
            :label="item.label"
            :width="item.width || ''"
            :property="item.prop"
            :fixed="item.fixed"
            :show-overflow-tooltip="true"
          >
            <template v-if="item.prop === 'assistUnitPrice'" slot="header">
              <span style="color: red">*</span><span>辅进价</span>
            </template>
            <template v-if="item.prop === 'deliveryDate'" slot="header">
              <span style="color: red">*</span><span>交货期</span>
            </template>
            <template v-if="item.prop === 'assistSkuNum'" slot="header">
              <span style="color: red">*</span><span>辅数量</span>
            </template>
            <template v-if="item.prop === 'workableArrivalTime'" slot="header">
              <span style="color: red">*</span><span>落实到货时间</span>
            </template>
            <template v-if="item.prop === 'priceExpireTime'" slot="header">
              <span style="color: red">*</span><span>价格有效期</span>
            </template>
            <!-- <template v-if="isRenderCheckBox(item.prop)" slot="header">
              <el-checkbox @change="(val) => { batchUpdateCheckVal(val, item.prop) }" /><span class="ml-5">{{item.label}}</span>
            </template> -->
            <template v-if="item.prop === 'certificate'" slot="header">
              <el-checkbox v-model="qualification.certificate" @change="(val) => { batchUpdateCheckVal(val, item.prop) }" /><span class="ml-5">{{item.label}}</span>
            </template>
            <template v-if="item.prop === 'testReport'" slot="header">
              <el-checkbox v-model="qualification.testReport" @change="(val) => { batchUpdateCheckVal(val, item.prop) }" /><span class="ml-5">{{item.label}}</span>
            </template>
            <template v-if="item.prop === 'threeC'" slot="header">
              <el-checkbox v-model="qualification.threeC" @change="(val) => { batchUpdateCheckVal(val, item.prop) }" /><span class="ml-5">{{item.label}}</span>
            </template>
            <template v-if="item.prop === 'materialList'" slot="header">
              <el-checkbox v-model="qualification.materialList" @change="(val) => { batchUpdateCheckVal(val, item.prop) }" /><span class="ml-5">{{item.label}}</span>
            </template>
            <!-- 辅进价 -->
            <template v-if="item.prop === 'assistUnitPrice'" v-slot="scope">
              <el-input
                :ref="'assistUnitPrice' + scope.$index"
                v-model.trim="scope.row[scope.column.property]"
                :maxlength="32"
                @keyup.native="handleMoveFocus($event)"
                @input="
                  (val) => {
                    assistUnitPriceChange(
                      val,
                      scope.row,
                      scope.column.property
                    );
                  }
                "
              />
            </template>
            <!-- 辅数量 -->
            <template v-else-if="item.prop === 'assistSkuNum'" v-slot="scope">
              <el-input
                v-model.trim="scope.row[scope.column.property]"
                :disabled="!!scope.row.isSingleMeter"
                @input="
                  (val) => {
                    assistSkuNumChange(val, scope.row, scope.column.property);
                  }
                "
              />
            </template>
            <!-- 交货期 -->
            <template v-else-if="item.prop === 'deliveryDate'" v-slot="scope">
              <el-input
                v-model.number.trim="scope.row[scope.column.property]"
                @keyup.native="handleMoveFocus($event)"
                :maxlength="32"
              />
            </template>
            <!-- 资质全选 -->
            <template v-else-if="item.prop === 'selectAllQualification'" v-slot="scope">
              <el-checkbox v-model="scope.row[scope.column.property]" @change="(val) => { handleSelectAllQualification(val, scope.row) }" />
            </template>
            <!-- 落实到货时间 -->
            <template
              v-else-if="item.prop === 'workableArrivalTime'"
              v-slot="scope"
            >
              <el-date-picker
                v-model="scope.row[scope.column.property]"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="'23:59:59'"
              >
              </el-date-picker>
            </template>
            <!-- 价格有效期 -->
            <template
              v-else-if="item.prop === 'priceExpireTime'"
              v-slot="scope"
            >
              <el-date-picker
                v-model="scope.row[scope.column.property]"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="'23:59:59'"
              >
              </el-date-picker>
            </template>
            <!-- 备注 -->
            <template v-else-if="item.prop === 'remark'" v-slot="scope">
              <el-input
                v-model.trim="scope.row[scope.column.property]"
                @keyup.native="handleMoveFocus($event)"
                :maxlength="100"
              />
            </template>
            <template v-else-if="isRenderCheckBox(item.prop)" v-slot="scope">
              <el-checkbox
                v-model="scope.row[scope.column.property]"
                @change="checkChange"
              />
            </template>
            <template v-else slot-scope="scope">
              <span>{{ scope.row[item.prop] }}</span>
            </template>
          </pl-table-column>
        </pl-table>
      </div>
      <div class="footer">
        <div>
          <span>合计金额小写：{{ allSkuTotalPrice }}元</span>
        </div>
        <div>
          <span>合计金额大写：{{ allSkuTotalPriceStr }}</span>
        </div>
      </div>
    </el-card>
  </basic-dialog>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import BasicDialog from '../../../components/BasicDialog';
import * as bizUtil from '../../utils/index';
import { handleOpenNewPage } from '@/utils/bizUtils'

export default {
  name: 'QuoteDialog',
  components: {
    BasicDialog
  },
  props: {
    dialogVisible: {
      type: Boolean
    },
    isSynergy: {
      type: Boolean
    },
    isQuoteDone: {
      type: Boolean
    }
  },
  data () {
    return {
      qualification: {
        threeC: false,
        certificate: false,
        testReport: false,
        materialList: false
      },
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < new Date().getTime() - 86400000;
        }
      },
      workableArrivalTime: '',
      deliveryDate: '',
      priceExpireTime: '',
      queryParams: {
        isEdit: '',
        pageType: '',
        sourcingBillId: '',
        isDemand: false
      },
      importBtnLoading: false,
      tableLoading: false,
      dataList: [],
      undertakerArr: bizUtil.UNDERTAKER_ARR,
      invoiceTypeArr: bizUtil.INVOICE_TYPE_ARR,
      formValidate: {
        freightPayer: [
          { required: true, message: '运费承担方不能为空', trigger: 'change' }
        ],
        invoiceType: [
          { required: true, message: '发票类型不能为空', trigger: 'change' }
        ],
        taxRate: [
          { required: true, message: '税率不能为空', trigger: 'change' }
        ],
        freightPrice: [
          {
            pattern: /^\d+(\.{0,1}\d+){0,1}$/,
            message: '请输入正确格式运费',
            trigger: 'change'
          }
        ]
      },
      columns: []
    };
  },

  computed: {
    ...mapState('sourcing/purchaseDetail', {
      sourcingSkuQuoteList: (state) =>
        state.sourcingSkuQuoteList,
      sourcingSupplierDto: (state) => state.sourcingSupplierDto,
      allSkuTotalPrice: (state) => state.allSkuTotalPrice, // 合计金额小写
      allSkuTotalPriceStr: (state) => state.allSkuTotalPriceStr, // 合计金额大写
      invoiceTypeList: (state) => state.invoiceTypeList, // 发票类型
      taxRateList: (state) => state.taxRateList, // 税率
      freightBearerList: (state) => state.freightBearerList, // 运费承担方
      addQuotationLoading: (state) => state.addQuotationLoading, // 提交报价loading
      computingCostsLoading: (state) =>
        state.computingCostsLoading, // 运费分摊loading
      isMulttaxRate: (state) => state.isMulttaxRate, // 是否多计量
      taxRate2List: (state) => state.taxRate2List, // 多税率
      tmpQuotationLoading: (state) => state.tmpQuotationLoading // 暂存报价loading
    }),

    quoteForm () {
      return this.sourcingSupplierDto || {};
    },

    visible () {
      return this.dialogVisible;
    },
    // 增值税专用发票
    taxrateArr () {
      return this.quoteForm.invoiceType == bizUtil.INVOICE_TYPE_SPECIAL_CODE
        ? this.taxRateList.slice(1, 10)
        : this.taxRateList.slice(0, 1);
    },

    fileParam () {
      return {
        sourceBillId: this.queryParams.sourcingBillId,
        sourceSupplierId: this.sourcingSkuQuoteList[0]
          ? this.sourcingSkuQuoteList[0].sourcingSupplierId
          : ''
      };
    },
    taxRate2ListObj () {
      return this.taxRateList.filter((item) => {
        return this.taxRate2List.includes(item.sysTypeId + '');
      });
    }
  },
  created () {
    const detailInfo = JSON.parse(sessionStorage.getItem('detailInfo'));
    this.queryParams = { ...detailInfo };
    if (this.queryParams.pageType === 1) {
      this.columns = bizUtil.QUOTE_COLUMNS_INQUERY;
    } else {
      this.columns = bizUtil.QUOTE_COLUMNS_ORDER;
    }
  },
  methods: {
    ...mapActions('sourcing/purchaseDetail', ['shareFreight']),
    // 查询定标记录
    handleSearchBidRecord () {
      const skuCodeList = this.sourcingSkuQuoteList.map(item => item.skuCode).filter(item => !!item)
      if (skuCodeList.length == 0) {
        return this.$message.warning('无商品代码商品无定标记录')
      }
      console.log(skuCodeList)
      localStorage.setItem('sourcing_record_skus', JSON.stringify(skuCodeList))
      const { pageType } = this.queryParams;
      // 1 询价 2 订货
      handleOpenNewPage(this, { name: 'bidRecord', query: { source: 2, billType: pageType } })
    },
    // 关闭弹框清空勾选状态
    handleClosed () {
      this.qualification = {
        threeC: false,
        certificate: false,
        testReport: false,
        materialList: false
      }
    },
    shareFreightAction (data) {
      this.shareFreight({
        payload: {
          data
        }
      });
    },

    freightPayerChange (val) {
      this.quoteForm.freightPrice = 0;
    },

    invoiceTypeChange (val) {
      if (val !== bizUtil.INVOICE_TYPE_SPECIAL_CODE) {
        this.quoteForm.taxRate = bizUtil.TAXRATE_39874_CODE;
      } else {
        this.quoteForm.taxRate = '';
      }
    },
    // 落实到货时间统一配置
    dateTimeChange (val) {
      if (Number(new Date(val) < Number(new Date()))) {
        return this.$message.warning('落实到货时间不能小于当前时间');
      }
      if (val) {
        this.sourcingSkuQuoteList.forEach((item) => {
          item.workableArrivalTime = val;
        });
      }
    },
    // 批量维护交货期
    deliveryDateChange (val) {
      if (val) {
        this.sourcingSkuQuoteList.forEach((item) => {
          item.deliveryDate = val;
        });
      }
    },

    // 批量维护报价有效期
    priceExpireTimeChange (val) {
      if (val) {
        this.sourcingSkuQuoteList.forEach((item) => {
          item.priceExpireTime = val;
        });
      }
    },

    isRenderCheckBox (val) {
      const checkList = ['threeC', 'certificate', 'testReport', 'materialList'];
      return checkList.includes(val);
    },
    // 批量更新 合格证、3c、检测报告、材质单勾选状态
    batchUpdateCheckVal (val, key) {
      this.sourcingSkuQuoteList.forEach((item) => {
        item[key] = val;
      });
    },
    // 批量更新 合格证、3c、检测报告、材质单勾选状态
    handleSelectAllQualification (val, row) {
      row.threeC = val;
      row.certificate = val;
      row.testReport = val;
      row.materialList = val;
    },
    // 分摊运费
    handleShareFreight () {
      this.$refs.quoteForm.validate((valid) => {
        if (valid) {
          const skuQuotes = this.sourcingSkuQuoteList.map((item) => ({
            sourcingSkuQuoteId: item.sourcingSkuQuoteId,
            skuUnit: item.skuUnit,
            assistSkuUnit: item.assistSkuUnit,
            skuNum: item.skuNum,
            assistSkuNum: item.assistSkuNum,
            unitPrice: item.unitPrice || 0,
            assistUnitPrice: item.assistUnitPrice || 0,
            addPriceType: item.addPriceType,
            rebateRatio: item.rebateRatio,
          }));
          const {
            freightPayer,
            freightPrice,
            invoiceType,
            taxRate,
          } = this.quoteForm;
          const params = {
            freightPayer,
            freightPrice: Number(freightPrice),
            invoiceType,
            taxRate,
            skuQuotes
          };
          this.shareFreightAction(params);
        }
      });
    },
    // 导出
    handleExportQuoteDtl () {
      let sourceBillId = this.queryParams.sourcingBillId;
      let sourceSupplierId = this.sourcingSkuQuoteList[0].sourcingSupplierId;
      if (sourceBillId && sourceSupplierId) {
        window.location.href = `${window.location.origin}/srm-api/sourceSkuQuote/exportSkuQuote?sourceBillId=${sourceBillId}&sourceSupplierId=${sourceSupplierId}`;
      } else {
        this.$message.error('导出异常');
      }
    },
    // 辅进价change
    assistUnitPriceChange (val, row, prop) {
      row[prop] = this.formatInputVal(val);
      if (row.isSingleMeter) {
        row.unitPrice = row[prop];
      } else {
        row.unitPrice = bizUtil.toFixed(
          (row[prop] * row.assistSkuNum) / row.skuNum,
          3
        );
      }
    },

    handleMoveFocus (event) {
      let curel = document.activeElement; // 当前input元素
      let curtTd = curel.parentElement.parentElement.parentElement;
      let curcellIndex = curtTd.cellIndex; // 当前元素行单元格索引
      let curtTr = curtTd.parentElement; // 当前tr
      let curRowIndex = curtTr.sectionRowIndex; // 当前元素行的索引；
      let curtbody = curtTr.parentElement.children; // 当前tbody内容的整个表单
      // 向上
      if (event.keyCode == 38) {
        if (curRowIndex - 1 >= 0) {
          curtbody[curRowIndex - 1].children[curcellIndex].querySelector('.el-input__inner').focus()
        }
      }
      // 向下
      if (event.keyCode == 40) {
        if (curRowIndex + 1 !== curtbody.length) {
          curtbody[curRowIndex + 1].children[curcellIndex].querySelector('.el-input__inner').focus()
        }
      }
      // 向右
      if (event.keyCode === 39) {
        const rightInput = curtTr.children[curcellIndex + 1].querySelector('.el-input__inner');
        if (rightInput) {
          rightInput.focus()
        }
      }
      // 向左
      if (event.keyCode === 37) {
        const leftInput = curtTr.children[curcellIndex - 1].querySelector('.el-input__inner');
        if (leftInput) {
          leftInput.focus()
        }
      }
    },

    // 辅数量change
    assistSkuNumChange (val, row, prop) {
      row[prop] = this.formatInputVal(val);
      if (row.isSingleMeter) {
        row.skuNum = row[prop];
      } else {
        row.unitPrice = bizUtil.toFixed(
          (row.assistUnitPrice * row[prop]) / row.skuNum,
          3
        );
      }
    },

    checkChange (value) {},
    // 判断已填写单价但未填写交货期
    isEmptyDeliveryDate (data) {
      return data.some((item) => !item.deliveryDate);
    },
    // 判断已填写单价但未填写落实到货时间
    isEmptyArrivalTime (data) {
      return data.some((item) => !item.workableArrivalTime);
    },
    handleSubmitTempQuote () {
      this.handleFinishQuote('temp');
    },
    // 完成报价 temp-handler 暂存，save-handler 完成报价
    handleFinishQuote (type) {
      this.workableArrivalTime = '';
      this.deliveryDate = '';
      this.priceExpireTime = '';
      let handlerName = 'save-handler';
      if (type === 'temp') {
        handlerName = 'temp-handler';
      } else {
        handlerName = 'save-handler';
      }
      this.$refs.quoteForm.validate((valid) => {
        if (valid) {
          this.quoteForm.freightPrice = Number(this.quoteForm.freightPrice);
          if (this.isSynergy) {
            let synergySubmitData = this.sourcingSkuQuoteList.filter(item => item.skuStatus == 200)
            synergySubmitData.forEach((item) => {
              item.threeC = item.threeC === true ? 1 : 0;
              item.certificate = item.certificate === true ? 1 : 0;
              item.testReport = item.testReport === true ? 1 : 0;
              item.materialList = item.materialList === true ? 1 : 0;
            });
            const params = {
              billType: this.queryParams.pageType,
              checkFillPrice: false,
              sourcingSupplierDto: {
                sourcingBillId: this.queryParams.sourcingBillId,
                ...this.quoteForm
              },
              sourcingSkuQuoteList: synergySubmitData
            };
            this.$emit(handlerName, params);
            return;
          }
          let submitData = this.sourcingSkuQuoteList.map((item) => ({
            ...item
          }));
          let submitSkuQuoteList = submitData.filter(
            (item) => item.unitPrice && item.unitPrice != 0
          );
          // 检验单价
          if (submitSkuQuoteList.length === 0) {
            return this.$message.warning('请填写单价');
          }
          // 校验交货期
          if (
            this.isInquery() &&
            this.isEmptyDeliveryDate(submitSkuQuoteList)
          ) {
            return this.$message.warning('报价商品需填写交货期');
          }
          // 校验落实到货期
          if (
            !this.isInquery() &&
            this.isEmptyArrivalTime(submitSkuQuoteList)
          ) {
            return this.$message.warning('报价商品需填写落实到货时间');
          }
          submitSkuQuoteList.forEach((item) => {
            item.threeC = item.threeC === true ? 1 : 0;
            item.certificate = item.certificate === true ? 1 : 0;
            item.testReport = item.testReport === true ? 1 : 0;
            item.materialList = item.materialList === true ? 1 : 0;
          });
          const payload = {
            billType: this.queryParams.pageType,
            checkFillPrice: false,
            sourcingSupplierDto: {
              sourcingBillId: this.queryParams.sourcingBillId,
              ...this.quoteForm
            },
            sourcingSkuQuoteList: this.isSynergy ? this.sourcingSkuQuoteList : submitSkuQuoteList
          };
          // 供应商为我司且运费 = 0
          if (
            handlerName == 'save-handler' &&
            this.quoteForm.freightPayer == bizUtil.UNDERTAKER_SELF_CODE &&
            this.quoteForm.freightPrice <= 0
          ) {
            return this.$confirm(
              '供应商为我司承担运费，请先落实运费后再进行报价完成',
              '提示',
              {
                type: 'warning'
              }
            )
              .then(() => {
                if (submitData.some((item) => !item.unitPrice)) {
                  return this.$confirm(
                    '存在未报价商品，您确定要完成报价吗?',
                    '提示',
                    {
                      type: 'warning'
                    }
                  )
                    .then(() => {
                      this.$emit(handlerName, payload);
                    })
                    .catch(() => {});
                } else {
                  this.$emit(handlerName, payload);
                }
              })
              .catch(() => {});
          }
          if (
            handlerName == 'save-handler' &&
            submitData.some((item) => !item.unitPrice)
          ) {
            return this.$confirm(
              '存在未报价商品，您确定要完成报价吗?',
              '提示',
              {
                type: 'warning'
              }
            )
              .then(() => {
                this.$emit(handlerName, payload);
              })
              .catch(() => {});
          }
          this.$emit(handlerName, payload);
        }
      });
    },
    // 取消报价
    handleCancelQuote () {
      if (this.$refs.quoteForm) {
        this.$refs.quoteForm.resetFields();
      }
      this.$emit('hide-handler');
    },
    // 上传校验
    beforeFileUploadForBatch (file) {
      this.importBtnLoading = true;
      const fileExt = file.name.replace(/.+\./, '');
      const fileTypeArr = ['xls', 'xlsx'];
      const isRightType = fileTypeArr.includes(fileExt.toLowerCase());
      if (!isRightType) {
        this.$message.error('请上传.xls、.xlsx格式的文件!');
        this.importBtnLoading = false;
      }
      return isRightType;
    },
    // 上传成功
    onUploadsuccessForBatch (res) {
      this.importBtnLoading = false;
      if (!bizUtil.isResponseSuccess(res)) {
        this.$message.error(res.msg || '操作失败');
      } else {
        this.$message.success('导入成功');
        this.$emit(
          'query-handler',
          this.sourcingSkuQuoteList[0]
        );
      }
    },

    onUploadErrorForBatch () {
      this.importBtnLoading = false;
      this.$message.error('导入失败，请重试。');
    },
    // 其他运费承运商 不为我司承担 运费禁止编辑
    isOtherUndertaker () {
      return this.quoteForm.freightPayer !== bizUtil.UNDERTAKER_SELF_CODE;
    },

    // 是合格供应商 发票类型不能编辑
    isEligibleSupplier () {
      return (
        this.quoteForm.supplierStatus == bizUtil.SUPPLIER_QUALIFIED_STATUS_CODE
      );
    },

    // 是否为询价采购或需求
    isInquery () {
      return this.queryParams.pageType === 1;
    },
    // 格式化数字输入
    formatInputVal (value) {
      return (
        ('' + value)
          // eslint-disable-next-line no-useless-escape
          .replace(/[^\d^\.]+/g, '') // 第二步：把不是数字，不是小数点的过滤掉
          .replace(/^0+(\d)/, '$1') // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
          .replace(/^\./, '0.') // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
          .match(/^\d*(\.?\d{0,3})/g)[0] || ''
      ); // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到3位小数
    }
  }
};
</script>
<style lang='less' scoped>
.operating-area {
  .search-btn {
    margin-right: 10px;
  }
  float: right;
  .time-picker {
    color: #303133;
    display: inline;
    margin-right: 20px;
  }
}
.upload-quote {
  display: inline;
  margin-left: 10px;
}
.box-card {
  .quote-info-detail {
    line-height: 28px;
  }
}
.clear {
  clear: both;
}
.edit-table {
  margin: 20px 0;
}
.footer {
  span {
    font-size: 14px;
  }
}
.form-wrap:after {
  content: "";
  display: block;
  visibility: hidden;
  clear: both;
}
.ml-5 {
  margin-left: 5px;
}
</style>
